package com.plz.afmt.controller;

import com.alibaba.fastjson2.JSON;
import com.plz.afmt.dto.EnterprisesDto;
import com.plz.afmt.dto.EnterprisesQueryDto;
import com.plz.afmt.dto.QuestionDTO;
import com.plz.afmt.entity.UserEntity;
import com.plz.afmt.service.ChatService;
import com.plz.afmt.service.EnterprisesService;
import com.plz.afmt.service.UserService;
import com.plz.afmt.user.model.dto.UserDTO;
import com.plz.afmt.vo.ChatVO;
import com.plz.afmt.vo.EnterprisesVo;
import com.plz.shrio.utils.UserMangerUtil;
import com.plz.web.base.controller.BaseController;
import com.plz.web.base.dto.*;
import com.plz.web.base.vo.PagerResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.Valid;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 企业表 管理
 * </p>
 *
 * @author jzc
 */
@Slf4j
@RestController
@Api(tags = "ai对话")
@RequestMapping("/admin/chat")
public class ChatController extends BaseController {

    @Autowired
    private ChatService chatByCoseService;
    @Autowired
    private UserService userService;

    /**
     * Chat-创建会话
     *
     * @return 创建chat 结果
     */
    @ApiOperation(value = "chat-创建会话", notes = "创建对话")
    @PostMapping(value = "/create")
    public Resp<Boolean> createCoze() {
        Boolean chat = chatByCoseService.createChat();
        return getRes(chat);
    }


    /**
     * Chat-进行对话
     *
     * @return 进行对话结果
     */
    @ApiOperation(value = "chat-进行对话", notes = "进行对话")
    @PostMapping(value = "/question")
    public SseEmitter chatByCoze(@Valid @RequestBody Resq<BaseCodeDto> requestBean) {
        BaseCodeDto dto = getReqData(requestBean);

        // TODO 后期载入分布式锁，防止用户发起多次提问
        // String lockKey = "ChatSSELock:" + question.getChatId();
        // RLock lock = redissonClient.getLock(lockKey);
        // lock.lock(100, TimeUnit.SECONDS);

        // 创建SseEmitter对象，注意这里的timeout是发送时间，不是超时时间，网上的文档有问题
        System.out.println("控制层接收问题："+dto.getCode());
        SseEmitter emitter = new SseEmitter(1800000L);
        emitter.onCompletion(() -> {
            System.out.println("SSE连接已关闭");
        });
        emitter.onTimeout(() -> {
            System.out.println("SSE连接已超时");
        });

        UserEntity userEntity = userService.getById(UserMangerUtil.getUserId());
        if(userEntity.getSessionId()==null){
            chatByCoseService.createChat();
            userEntity = userService.getById(UserMangerUtil.getUserId());
        }
//        // 处理未正常提供chatId的情况
//        try {
//            String formatted = DateTimeFormatter.ISO_INSTANT.format(ZonedDateTime.now());
//            // 构造并反馈提示
//            ChatVO chatVO = ChatVO.builder().isFinish(false).userId(null)
//                    .answer("请正确创建提问并刷新网页").chatId(null).date(formatted)
//                    .build();
//            String sendData = JSON.toJSONString(chatVO);
//            emitter.send(SseEmitter.event().data(sendData));
//            // 结束
//            chatVO.setIsFinish(true);
//            sendData = JSON.toJSONString(chatVO);
//            emitter.send(SseEmitter.event().data(sendData));
//            emitter.complete();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        String answer = chatByCoseService.question(emitter, dto.getCode(), userEntity);
        // chatByLlamaService.questionDTO(emitter); // ollama 存在问题，先不要用
        return emitter;
    }


}
